import Vue from 'vue'

// 用户认证模块
const state = {
  token: '',
  user: {},
  isAuthenticated: false
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    state.isAuthenticated = !!token
    if (token) {
      localStorage.setItem('token', token)
    } else {
      localStorage.removeItem('token')
    }
  },
  SET_USER(state, user) {
    state.user = user
    if (user && Object.keys(user).length > 0) {
      localStorage.setItem('user', JSON.stringify(user))
    } else {
      localStorage.removeItem('user')
    }
  },
  LOGOUT(state) {
    state.token = ''
    state.user = {}
    state.isAuthenticated = false
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }
}

const actions = {
  // 登录
  login({ commit }, { username, password }) {
    return new Promise((resolve, reject) => {
      Vue.prototype.$userapi.login({ username, password })
        .then(response => {
          if ((response.code === '200' || response.code === 200) && response.data) {
            const rawUser = response.data.user || response.data;
            // 统一 user 字段结构
            const user = {
              username: rawUser.userName || rawUser.username || '',
              role: rawUser.role === '1' ? 'admin' : 'user',
              ...rawUser
            };
            const token = 'fake-token';
            commit('SET_TOKEN', token);
            commit('SET_USER', user);
            resolve({ token, user });
          } else {
            reject(new Error(response.msg || '登录失败'));
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  
  // 登出
  logout({ commit }) {
    commit('LOGOUT')
    return Promise.resolve()
  },
  
  // 检查认证状态
  checkAuth({ state, commit }) {
    if (state.token && state.isAuthenticated) {
      return Promise.resolve(state.user)
    } else {
      commit('LOGOUT')
      return Promise.reject(new Error('未登录或登录已过期'))
    }
  }
}

const getters = {
  isAuthenticated: state => state.isAuthenticated,
  currentUser: state => state.user,
  token: state => state.token,
  userRole: state => state.user.role || ''
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
